﻿using ConfExpert.Forms.Base;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevTeam;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Sistem
{
    public partial class MusteriAday : XForm
    {

        string kategori;
        string FileToSend;
        public MusteriAday()
        {
            kategori = "MusteriAday";
            InitializeComponent();
        }

        private void MusteriAday_Load(object sender, EventArgs e)
        {
            this.Text = "Müşteri Adayları Listesi";

            gridView1.Init("GetCustomerCandidate");  // ali_GetCustomers

            gridView1.AddAutoIncrementalPK("CustomerCandidateId");

            gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gridView1.AddColumn("EkliDosya", typeof(string), "IIF(NotlarId>0,'VAR',null)");  //.SetCaptions("NotlarId:EkliDosya");
            gridView1.MakeColumnInvisible("CustomerCandidateId", "NotlarId");
            gridView1.MakeRowSelectable();
            gridView1.MakeColumnsReadOnly("EkliDosya");

            gridView1.AddDetailGrid(gridView2, "CustomerCandidateId");
            gridView2.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            gridView2.MakeColumnInvisible("ContactId");

            gridView1.YanYanaGetir("EkliDosya:Name");
            gridView1.YanYanaGetir("TeslimSekliSId:TestRequirement");

            GridManager gm = GridManager.GetManager(gridView1);
            gm.GridMenu.AddMenu("Aç", Ac);
            gm.GridMenu.AddMenu("Ekle", Ekle);
            gm.GridMenu.AddMenu("Değiştir", Degistir);
            gm.GridMenu.AddMenu("Sil", Sil);

            gridView1.BestFitColumns();
            gridView2.BestFitColumns();

            btnKaydet.ItemClick += btnKaydet_ItemClick;
            this.Shown += MusteriAday_Shown;

            gridView1.Columns["EkliDosya"].ColumnEdit = riHyperLink;
            gridView1.RowCellClick += gridView2_RowCellClick;

            gridView2.EnableRowDelete();
        }

        RepositoryItemHyperLinkEdit riHyperLink = new RepositoryItemHyperLinkEdit();

        void gridView2_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            Cursor.Current = Cursors.WaitCursor;

            DataRow dr = gridView1.GetDataRow(e.RowHandle);

            switch (e.Column.FieldName)
            {
                case "EkliDosya":
                    int NotlarId = gridView1.GetDataRow(gridView1.FocusedRowHandle)["NotlarId"].ToInt();
                    if (NotlarId > 0)
                    {
                        DataTable t = Session.DataManager.ExecuteDataTable("GetNotlar", kategori, NotlarId);
                        FileToSend = ByteArrayToFile3(t.Rows[0]["DosyaAdi"].ToString(), t.Rows[0]["BLOB"] as byte[]);

                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo.FileName = FileToSend;
                        process.Start();
                    }
                    break;
            }


            Cursor.Current = Cursors.Default;
        }

        void MusteriAday_Shown(object sender, EventArgs e)
        {
            splitContainerControl1.AutoSize(0.7);
        }

        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.UpdateAll("", "CustomerCandidate", "ContactId,CustomerCandidateId,Title,Name,Email,Phone,Mobile", "Contact");
        }

        void Ac(object sender, EventArgs e)
        {
            int NotlarId = gridView1.GetDataRow(gridView1.FocusedRowHandle)["NotlarId"].ToInt();
            if (NotlarId > 0)
            {
                DataTable t = Session.DataManager.ExecuteDataTable("GetNotlar", kategori, NotlarId);
                FileToSend = ByteArrayToFile3(t.Rows[0]["DosyaAdi"].ToString(), t.Rows[0]["BLOB"] as byte[]);

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = FileToSend;
                process.Start();
            }
        }

        void Rfrsh()
        {
            gridView1.RefreshDataSource("GetCustomerCandidate");
            gridView1.BestFitColumns();
        }

        void Degistir(object sender, EventArgs e)
        {
            int NotlarId = gridView1.GetDataRow(gridView1.FocusedRowHandle)["NotlarId"].ToInt();
            int CustomerCandidateId = gridView1.GetDataRow(gridView1.FocusedRowHandle)["CustomerCandidateId"].ToInt();
            if (NotlarId > 0)
            {
                using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                        if (openFileDialog1.OpenFile() != null)
                        {
                            string FileName = Path.GetFileName(openFileDialog1.FileName),
                                Extension = Path.GetExtension(openFileDialog1.FileName);
                            byte[] bArr = FileManager.Read(openFileDialog1.FileName);
                            ExecuteNonQuery("UpdNotlar", kategori, NotlarId, openFileDialog1.SafeFileName, bArr, WhoAmI);
                            ExecuteNonQuery("UpdCustomerCandidateNotlar", CustomerCandidateId, NotlarId);
                            Notify("Dosya güncellendi.");
                            Rfrsh();
                        }
            }
        }

        public string ByteArrayToFile3(string filePath, byte[] content)
        {
            string FullPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\" + filePath;
            using (FileStream fs = new FileStream(FullPath, FileMode.Create, FileAccess.Write))
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                bw.Write(content);
                bw.Flush();
            }
            return FullPath;
        }


        void Ekle(object sender, EventArgs e)
        {
            int NotlarId;
            int CustomerCandidateId = gridView1.GetDataRow(gridView1.FocusedRowHandle)["CustomerCandidateId"].ToInt();

            using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    if (openFileDialog1.OpenFile() != null)
                    {
                        string FileName = Path.GetFileName(openFileDialog1.FileName),
                            Extension = Path.GetExtension(openFileDialog1.FileName);
                        byte[] bArr = FileManager.Read(openFileDialog1.FileName);
                        NotlarId = ExecuteScalar("UpdNotlarMusteriAday", kategori, 0, openFileDialog1.SafeFileName, bArr, WhoAmI).ToInt();
                        ExecuteNonQuery("UpdCustomerCandidateNotlar", CustomerCandidateId, NotlarId);
                        Notify("Dosya eklendi.");
                        Rfrsh();
                    }

        }

        void Sil(object sender, EventArgs e)
        {
            int NotlarId = gridView1.GetDataRow(gridView1.FocusedRowHandle)["NotlarId"].ToInt();
            int CustomerCandidateId = gridView1.GetDataRow(gridView1.FocusedRowHandle)["CustomerCandidateId"].ToInt();
            if (NotlarId > 0)
                if (XtraMessageBox.Show("Bu dosyayı silmek istediğinizden emin misiniz?", "Teyid", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    ExecuteNonQuery("DelNotlarMusteriAday", kategori, NotlarId, CustomerCandidateId);
                    Notify("Dosya silindi.");
                    Rfrsh();
                }
        }

    }
}
